<template>
  <div class="bound-scenic">
    <div v-if="!Disabled" class="selected scenic-page">
      <el-form
        ref="listFilterRef"
        :model="list.filter"
        inline
        class="list-filter"
        size="mini"
        style="margin-bottom: 2px"
      >
        <el-form-item prop="activityName">
          <el-input
            v-model="list.filter.activityName"
            placeholder="活动名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-pagination
          v-bind="elPaginationProps"
          :total="list.total"
          :currentPage.sync="list.filter.pageNo"
          :pageSize.sync="list.filter.pageSize"
          size="mini"
        />
      </div>
      <el-table
        @selection-change="handleSelectionChange"
        height="418"
        v-loading="list.loading"
        :data="list.data"
        size="mini"
        ref="tableList"
      >
        <el-table-column label="活动名称" prop="activityName" />
        <el-table-column type="selection" width="55" />
      </el-table>
    </div>
    <div
      class="selected"
      :style="{
        width: Disabled ? '100%' : 'calc(34% - 10px)',
        marginLeft: Disabled ? '0' : '10px'
      }"
    >
      <h5>
        已关联活动
        <template v-if="selected.length > 0">
          （{{ selected.length }}）
        </template>
        <el-popconfirm
          v-if="selected.length > 0 && !Disabled"
          title="您确定要移除全部吗？"
          style="float: right; margin-right: 10px"
          @confirm="removeAll"
          @onConfirm="removeAll"
        >
          <el-button slot="reference" size="mini">移除全部</el-button>
        </el-popconfirm>
      </h5>
      <el-scrollbar v-if="selected.length > 0">
        <draggable
          v-model="selected"
          :disabled="Disabled"
          group="site"
          animation="300"
        >
          <div
            v-for="(item, index) in selected"
            :key="index"
            class="el-cascader-node selected-item"
          >
            <span class="el-cascader-node__label">{{ item.activityName }}</span>
            <i
              v-if="!Disabled"
              @click="toggleRowSelection(item, false)"
              class="el-icon-circle-close"
            />
          </div>
        </draggable>
      </el-scrollbar>
      <p v-else class="tips">
        <i class="el-icon-s-order"></i>
        暂未关联数据
      </p>
    </div>
  </div>
</template>

<script>
import pageMixin from '@/utils/pageMixin'
import useAdmateAdapter from '@/utils/useAdmateAdapter'
import draggable from 'vuedraggable'

export default {
  name: 'activity-spot',
  inject: {
    elForm: {
      default: ''
    }
  },
  mixins: [pageMixin],
  components: { draggable },
  props: {
    value: Array,
    selecteList: Array, // 已选择列表
    disabled: {
      type: Boolean,
      default: false
    },
    maxLength: {
      type: Number,
      default: 0
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  setup: () =>
    useAdmateAdapter({
      urlPrefix: 'one-travel-api/activity'
    }),
  data () {
    return {
      idKey: 'id',
      selected: [],
      lock: true
    }
  },
  computed: {
    Disabled () {
      return this.disabled || (this.elForm || {}).disabled
    }
  },
  watch: {
    selecteList: {
      immediate: true,
      handler (n) {
        if (Array.isArray(n) && n.length > 0 && this.selected.length === 0) {
          this.selected = n.map(item => {
            // 选中已选择的行
            this.toggleRowSelection(
              {
                id: item.id
              },
              true
            )
            return {
              activityName : item.name,
              id: item.id
            }
          })
        }
      }
    },
    selected (n) {
      let ids = n.map(item => item.id)
      this.$emit('change', ids)
    },
    // 列表状态改变
    'list.loading' (n) {
      this.$nextTick(() => {
        if (!n) {
          // 回显已选中的
          this.selected.forEach(item => {
            this.toggleRowSelection(item, true)
          })
        }
        // 加锁的原因是因为边个初始化时会调用handleSelectionChange并传入空数组，会清空已选择的内容
        this.lock = n
      })
    }
  },
  methods: {
    // 移除全部
    removeAll () {
      this.selected.reverse().forEach((item, index) => {
        this.toggleRowSelection(item, false)
      })
    },
    handleSizeChange (size) {
      this.list.filter.pageSize = size
      this.list.filter.pageNo = 1
      this.getList()
    },
    // 列表选择状态改变
    handleSelectionChange (e) {
      if (this.lock) {
        return // 锁住的，退出
      }
      // 先删除全部
      this.list.data.forEach(item => {
        this.removeItem(item)
      })
      e.forEach(item => {
        // 再添加
        this.addItem(item)
      })
    },
    // 是否已经勾选
    isSelected (row) {
      return this.selected.some(item => item[this.idKey] == row[this.idKey])
    },
    // 添加一项
    addItem (row) {
      this.selected.unshift(row)
      // 添加项超过了最大可添加项，删除最后一项
      if (this.maxLength > 0 && this.selected.length > this.maxLength) {
        let lastIndex = this.selected.length - 1
        this.toggleRowSelection(this.selected[lastIndex], false)
      }
      this.$forceUpdate()
    },
    // 删除一项
    removeItem (row) {
      this.selected = this.selected.filter(
        item => item[this.idKey] !== row[this.idKey]
      )
      this.$forceUpdate()
    },
    // 切换选中状态
    toggleRowSelection (row, status) {
      if (!status) {
        this.removeItem(row)
      }
      // 切换某一行的选中状态
      this.list.data.forEach(item => {
        if (row[this.idKey] === item[this.idKey]) {
          this.$refs.tableList.toggleRowSelection(item, status)
          return
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.bound-scenic {
  height: 506px;
  .selected {
    display: inline-block;
    width: calc(34% - 10px);
    height: 100%;
    border: solid 1px #dfe4ed;
    border-radius: 4px;
    margin-left: 10px;
    float: left;
    h5 {
      font-size: 14px;
      margin: 0;
      height: 36px;
      line-height: 36px;
      padding-left: 10px;
      background: #efefef;
      .el-checkbox {
        float: right;
        padding-right: 10px;
      }
    }
    .el-scrollbar {
      height: 470px;
    }
    .el-cascader-node {
      padding: 0;
      height: 36px;
      line-height: 36px;
      // border-bottom: 1px solid rgb(241, 241, 241);
      box-sizing: border-box;
      .el-icon-circle-close {
        float: right;
        margin-right: 20px;
        line-height: 40px;
        font-size: 18px;
      }
    }

    .tips {
      text-align: center;
      color: #ccc;
      padding-top: 100px;
      i {
        display: block;
        font-size: 60px;
      }
    }
    :deep(.el-scrollbar__wrap) {
      overflow-x: hidden;
      box-sizing: border-box;
    }
  }
  .scenic-page {
    display: inline-block;
    width: 66%;
    margin-left: 0;
    padding-top: 8px;
  }

  :deep(.el-form) {
    border: none;
    padding-left: 8px;
  }
  :deep(.el-form--inline:first-child > .el-form-item) {
    margin-bottom: 0;
  }
  :deep(.el-pagination__sizes) {
    width: 80px;
  }
  :deep(.el-pagination.is-background .btn-prev,
  .el-pagination.is-background .btn-next,
  .el-pagination.is-background .el-pager li) {
    max-width: 30px;
  }
  :deep(.el-pagination__jump .el-input) {
    width: 40px !important;
  }
  :deep(.el-table::before) {
    display: none;
  }
}
</style>